package com.tangyuan.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.tangyuan.common.convert.address.AddressConvert;
import com.tangyuan.common.exception.TangYuanException;
import com.tangyuan.common.result.ResultCodeEnum;
import com.tangyuan.common.util.PhoneNumberUtil;
import com.tangyuan.user.domain.dto.AddAgentReviewDTO;
import com.tangyuan.user.domain.po.AgentReview;
import com.tangyuan.user.mapper.AgentReviewMapper;
import com.tangyuan.user.service.IAgentReviewService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * <p>
 * 代理审核表 服务实现类
 * </p>
 *
 * @author Shuai
 * @since 2024-08-21
 */
@Service
@Slf4j
public class AgentReviewServiceImpl extends ServiceImpl<AgentReviewMapper, AgentReview> implements IAgentReviewService {

    private static final AddressConvert addressConvert = AddressConvert.INSTANCE;
    @Override
    public void addAgentReview(Long userId, AddAgentReviewDTO addAgentReviewDTO) {
        if (userId == null) {
            return;
        }
        boolean success = PhoneNumberUtil.isValidPhoneNumber(addAgentReviewDTO.getPhone());
        if (!success) {
            throw new TangYuanException(ResultCodeEnum.PHONE_NUMBER_IS_WRONG_FORMAT);
        }
        AgentReview one = lambdaQuery().eq(AgentReview::getUserId, userId).one();
        if (one == null) {
            String areaNameList = addressConvert.convertAreaIdToAreaName(addAgentReviewDTO.getAreaId().intValue());
            log.warn("打印传过来的街道信息：{}", areaNameList);
            String[] parts = areaNameList.split(" ");
            String street = parts[parts.length-1];

            AgentReview agentReview = new AgentReview();
            agentReview.setUserId(userId);
            agentReview.setStreet(street);
            agentReview.setPhone(addAgentReviewDTO.getPhone());
            agentReview.setApplicationDate(LocalDate.now());
            agentReview.setStatus(0);
            agentReview.setCreateTime(LocalDateTime.now());
            save(agentReview);
        }else {
            throw new TangYuanException(ResultCodeEnum.APPLICATION_AGENT_HAS_BEEN_SUBMITTED);
        }
    }
}
